﻿
CREATE FUNCTION [dbo].[GetStocIesiriData]
(
	@IDArticol int,
	@Pret decimal(25,5),
	@LaData datetime,
	@GestCantitativa bit	
)
RETURNS decimal(25,5)
AS
BEGIN
	DECLARE @ResultVar decimal(25,5)
	IF @GestCantitativa=0
	BEGIN
		SELECT @ResultVar = COALESCE(SUM(ddl.Cantitate),0) FROM DocumenteDetaliu dd 
		JOIN Documente d ON d.IDDocument=dd.IDDocument
		JOIN DocumenteDetaliuLink  ddl ON ddl.IDDocDetaliuSursa = dd.IDDocumentDetaliu
		JOIN DocumenteDetaliu ddr ON ddl.IDDocDetaliuDest = ddr.IDDocumentDetaliu
		JOIN Documente dr ON ddr.IDDocument = dr.IDDocument
		WHERE dd.IDArticol=@IDArticol AND dd.ValoareUnitara=@Pret AND 
		(d.IDTipDocument = 0 OR d.IDTipDocument = 15) AND d.AreDocGestStoc=1 AND 
		(dr.IDTipDocument in (1,13,14)) AND dr.AreDocGestStoc=1 AND dr.DataDoc<=@LaData
	END
	ELSE
	BEGIN
		SELECT @ResultVar = COALESCE(SUM(dd.Cantitate),0) 
		FROM DocumenteDetaliu dd 
		JOIN Documente d ON d.IDDocument=dd.IDDocument 
		--AND d.AreDocGestStoc=1 
		AND d.DataDoc<=@LaData
		JOIN TipDocument td ON d.IDTipDocument = td.IDTipDocument AND td.TipOperatie LIKE '%O%'  AND td.ModificaStoc=1 
		WHERE dd.IDArticol=@IDArticol 
		 
	END
	RETURN @ResultVar

END